package com.toe.common.utils;

import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class MemoryPaginationUtils {

    /**
     * 内存分页
     *
     * @param records  待分页的数据
     * @param pageNum  当前页码 >0
     * @param pageSize 每页显示的条数
     * @return 分页之后的数据
     */
    public static <T> List<T> pagination(List<T> records, int pageNum, int pageSize) {
        if (CollectionUtils.isEmpty(records)) {
            return Collections.emptyList();
        }
        if(pageNum <= 0){
            return Collections.emptyList();
        }
        int totalCount = records.size();
        System.out.println("pageSize -> "+pageSize);
        int remainder = totalCount % pageSize;
        int pageCount = (remainder > 0) ? totalCount / pageSize + 1 : totalCount / pageSize;
        if (remainder == 0) {
            return records.stream()
                    .skip((pageNum - 1) * pageSize)
                    .limit(pageSize)
                    .collect(Collectors.toList());
        } else {
            if (pageNum == pageCount) {
                return records.stream()
                        .skip((pageNum - 1) * pageSize)
                        .limit(totalCount)
                        .collect(Collectors.toList());
            } else {
                return records.stream()
                        .skip((pageNum - 1) * pageSize)
                        .limit(pageSize)
                        .collect(Collectors.toList());
            }
        }
    }

    /**
     * 得到总条数
     * @param list
     * @param <T>
     * @return
     */
    public static <T> long getTolCount(List<T> list) {
        return list.size();
    }

    /**
     * 得到总页数
     * @param list
     * @param pageSize
     * @param <T>
     * @return
     */
    public static <T> int getTolPageNum(List<T> list, int pageSize) {
        return getTolCount(list) % pageSize == 0
                ? (int) (getTolCount(list) / pageSize)
                : (int) (getTolCount(list) / pageSize + 1);
    }

    /**
     * 得到总页数
     * @param tolCount
     * @param pageSize
     * @return
     */
    public static int getTolPageNum(int tolCount, int pageSize) {
        return tolCount % pageSize == 0
                ? tolCount / pageSize
                : tolCount / pageSize + 1;
    }

}


